package cn.edgar.org.service.impl;


import cn.edgar.basic.service.impl.BaseServiceImpl;
import cn.edgar.basic.utils.PageList;
import cn.edgar.org.domain.Department;
import cn.edgar.org.mapper.DepartmentMapper;
import cn.edgar.org.query.DepartmentQuery;
import cn.edgar.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
// 只读事务
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        // 给dirPath拼接值
        String dirPath = "";
        if (department.getParent().getId() == null){
            // 如果parent对象为Null,说明他是顶级对象，那么dirPath就是他自己的主键id
            dirPath = "/" + department.getId();
        }else {
            // 否则他就有上级部门，那么我们需要查询到上级部门的对象，获取到上级部门的dirpath，拼接我自己的id，就是我的dirpath
            Department parentDept = departmentMapper.loadById(department.getParent().getId());
            if(parentDept != null){
                dirPath = parentDept.getDirPath() + "/" + department.getId();
            }
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        // 给dirPath拼接值
        String dirPath = "";
        if (department.getParent().getId() == null){
            // 如果parent对象为Null,说明他是顶级对象，那么dirPath就是他自己的主键id
            dirPath = "/" + department.getId();
        }else {
            // 否则他就有上级部门，那么我们需要查询到上级部门的对象，获取到上级部门的dirpath，拼接我自己的id，就是我的dirpath
            Department parentDept = departmentMapper.loadById(department.getParent().getId());
            if(parentDept != null){
                dirPath = parentDept.getDirPath() + "/" + department.getId();
            }
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }




    @Override
    public List<Department> tree() {
        // 查询所有部门的数据
        List<Department> depts = departmentMapper.loadAll();
        // 创建一个空集合
        List<Department> deptTree = new ArrayList<Department>();
        for (Department deptTmp : depts){
            if (deptTmp.getParent_id() == null){
                deptTree.add(deptTmp);
            }else {
                for (Department parent : depts){
                    if (parent.getId() == deptTmp.getParent_id()){
                        parent.getChildren().add(deptTmp);
                        break;
                    }
                }
            }
        }

        return deptTree;
    }


}
